package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.LoginDTO;
import com.sky.dto.RegDTO;
import com.sky.entity.Token;
import com.sky.entity.User;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.interceptor.JwtTokenAdminInterceptor;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.RegVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     * @param loginDTO
     * @return
     */
    public User login(LoginDTO loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (user.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return user;
    }

    /**
     * 注册
     * @param regDTO
     * @return
     */
    public RegVO reg(RegDTO regDTO) {
        String username = regDTO.getUsername();
        String password = regDTO.getPassword();
        String repassword = regDTO.getRepassword();
        //判断账号是否已经存在
        User discard = userMapper.getByUsername(username);
        //处理各种异常情况（账号已存在、确认密码不对）
        if (discard != null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_FOUND);
        }
        //判断密码与是否相同
        if (!password.equals(repassword)) {
            //密码不相同
            throw new AccountNotFoundException(MessageConstant.REPASSWORD_NOT_EQ);
        }
        //注册账号
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setStatus(1);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        boolean result = userMapper.insertReg(user);

        RegVO regVO =new RegVO();
        if (result){
            regVO.setMessage("注册成功");
        }else{
            throw new AccountNotFoundException(MessageConstant.UNKNOWN_ERROR);
        }
        String name = "用户" + user.getId();
        //为用户赋予初始用户名
        userMapper.insertNameById(user.getId(),name);
        return regVO;
    }

    /**
     * 获取用户信息
     * @return
     */
    public User userInfo() {
        //1、从请求头中获取令牌
        String tk = request.getHeader(jwtProperties.getUserTokenName());
        Token token = JSONObject.parseObject(tk, Token.class);
        //2、校验令牌,获取id
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token.getToken());
        Long empId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
        log.info("员工id:{}",empId);
        //3、根据id获取用户信息
        User user = userMapper.getUserById(empId);
        return user;
    }

}
